package 操作系统实验.实验一;/**
 * ************************************************************************
 * 项目名称: projectweb <br>
 * 文件名称:  <br>
 * 文件描述: 这里添加您的类文件描述，说明当前文件要包含的功能。 <br>
 * 文件创建：1913040634刘世锦  <br>
 * 创建时间: 2021/4/1 <br>
 *
 * @version v1.0 <br>
 * @update [序号][日期YYYY-MM-DD][更改人姓名][变更描述]<br>
 * ************************************************************************
 */

/**
 * @ProjectName: projectweb
 * @ClassName: b
 * @Description: 请描述该类的功能
 * @Author: 1913040634刘世锦
 * @Date: 2021/4/1 17:35 .
 * @version v1.0
 */
/*
 author by runoob.com
 ProducConsumerTest.java
 */

public class b {
    public static void main(String[] args) {
        CubbyHole c = new CubbyHole();
        Produc p1 = new Produc(c, 1);
        Consum c1 = new Consum(c, 1);
        p1.start();
        c1.start();
    }
}
class CubbyHole {
    private int contents;
    private boolean available = false;
    public synchronized int get() {
        while (available == false) {
            try {
                wait();
            }
            catch (InterruptedException e) {
            }
        }
        available = false;
        notifyAll();
        return contents;
    }
    public synchronized void put(int value) {
        while (available == true) {
            try {
                wait();
            }
            catch (InterruptedException e) {
            }
        }
        contents = value;
        available = true;
        notifyAll();
    }
}

class Consum extends Thread {
    private CubbyHole cubbyhole;
    private int number;
    public Consum(CubbyHole c, int number) {
        cubbyhole = c;
        this.number = number;
    }
    public void run() {
        int value = 0;
        for (int i = 0; i < 10; i++) {
            value = cubbyhole.get();
            System.out.println("消费者 #" + this.number+ " got: " + value);
        }
    }
}

class Produc extends Thread {
    private CubbyHole cubbyhole;
    private int number;

    public Produc(CubbyHole c, int number) {
        cubbyhole = c;
        this.number = number;
    }

    public void run() {
        for (int i = 0; i < 10; i++) {
            cubbyhole.put(i);
            System.out.println("生产者 #" + this.number + " put: " + i);
            try {
                sleep((int)(Math.random() * 100));
            } catch (InterruptedException e) { }
        }
    }
}